package org.smart4j.framework.Helper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.smart4j.framework.Util.ReflectionUtil;

/**
 * bean容器类，传入类名，即可获取实例化后的对象
 */
public final class BeanHelper {
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>,Object>();

    /**
     * 将bean实例放入Bean Map中
     * @param cls
     * @param object
     */
    public static void setBean(Class<?> cls, Object object){
        BEAN_MAP.put(cls,object);
    }

    /**
     * 定义bean map
     */
    static {
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        for (Class<?> beanClass: beanClassSet){
            Object obj = ReflectionUtil.newInstance(beanClass);
            //类名为key，实例化后的对象为value
            BEAN_MAP.put(beanClass,obj);
        }
    }

    /**
     * 获取bean map
     * @return
     */
    public static Map<Class<?>,Object> getBeanMap(){
        return BEAN_MAP;
    }

    /**
     * 获取bean实例
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> cls){
        if (!BEAN_MAP.containsKey(cls)){
            throw new RuntimeException("通过类"+cls +"获取实例化对象失败");
        }
        return (T) BEAN_MAP.get(cls);
    }
}
